<template>
  <div class="login-container">
    <!-- 左边 -->
    <div class="logo" />
    <!-- 右边 -->
    <div class="form">
      <h1>手机号登录</h1>
      <el-card shadow="never" class="login-card">
        <!-- 登录表单 -->
        <el-form v-if="currentLogin==='phone'" ref="loginRef" :model="loginForm" :rules="loginRules">
          <el-form-item prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="isAgree">
            <el-checkbox v-model="loginForm.isAgree">用户平台使用协议</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button style="width:350px" type="primary" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
        <!-- 二维码 -->
        <div v-else-if="currentLogin==='qrcode'" class="qrcode-login">
          <!-- 二维码 需要使用canvas的dom对象 -->
          <div v-if="codeState === 2" class="qrcode-layer scan_success">
            <span>用户已扫码</span>
            <i class="el-icon-check" />
          </div>
          <div v-else-if="codeState === 4" class="qrcode-layer timeout" @click="createCode">
            <span>二维码失效</span>
            <i class="el-icon-refresh-right" />
          </div>
          <div v-else-if="codeState === 5" class="qrcode-layer timeout" @click="createCode">
            <span>用户已取消</span>
            <i class="el-icon-refresh-right" />
          </div>
          <canvas ref="qrcodeCanvas" />
        </div>
        <el-row style="width: 350px;" type="flex" justify="space-between">
          <el-button size="small" style="width: 48%;" @click="changeLogin('phone')">手机号登录</el-button>
          <el-button size="small" style="width: 48%;" @click="changeLogin('qrcode')">扫码登录</el-button>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getQrcodeKeyApi, getQrCodeStateApi } from '@/api/user'
import QrCode from 'qrcode'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        mobile: process.env.NODE_ENV === 'development' ? '13800000002' : '',
        password: process.env.NODE_ENV === 'development' ? 'hm#qd@23!' : '',
        isAgree: process.env.NODE_ENV === 'development'
      },
      loginRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { patten: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度应该为6-16位之间', trigger: 'blur' }
        ],
        isAgree: [
          {
            validator: (rules, value, callback) => {
              value ? callback() : callback('没有勾选用户平台')
            }
          }
        ]
      },
      currentLogin: 'phone', // phone/qrcode
      qrCodeKey: '', // 加密串
      codeState: 1 // 正常状态
    }
  },
  watch: {
    currentLogin() {
      if (this.currentLogin === 'qrcode') {
        // 只要切换过来就生成
        this.createCode()
      } else {
        // 手机号登录
        clearInterval(this.timer) // 清理定时器
      }
    }
  },
  // 卸载前先把定时器取消掉
  beforeDestroy() {
    clearInterval(this.timer) // 清理定时器
  },
  methods: {
    // 1. 登录
    async login() {
      // 1.1登录校验
      await this.$refs.loginRef.validate()
      // 1.2 派发登录异步任务
      const { mobile, password } = this.loginForm
      this.$store.dispatch('user/login', { mobile, password })
    },
    // 声明切换方式
    changeLogin(mode) {
      this.currentLogin = mode
    },
    // 获取加密串的方法
    async getQrCodeKey() {
      this.qrCodeKey = await getQrcodeKeyApi()
    },
    // 生成二维码
    async createCode() {
      this.codeState = 1 // 此时重新开始
      await this.getQrCodeKey() // 生成二维码-此时一定有加密串 => 生成二维码
      // 此时已经有key了，要查了
      this.beginCheckLoop()
      QrCode.toCanvas(this.$refs.qrcodeCanvas, this.qrCodeKey, {
        width: 300,
        height: 300
      })
    },
    // 轮询-每隔一段时间就去服务器查一次
    beginCheckLoop() {
      // 检查逻辑
      const checkState = async() => {
        try {
          const { codeState, token } = await getQrCodeStateApi({ qrcode_key: this.qrCodeKey })
          // 登录成功-超时-取消关闭轮询
          this.codeState = codeState // 存储状态
          if (this.codeState === 4 || this.codeState === 5) {
            clearInterval(this.timer)
          } else if (this.codeState === 3) {
            clearInterval(this.timer)
            this.$store.commit('user/SET_TOKEN', token)
            this.$router.push('/dashboard')
          }
          // --------------------------
          console.log(codeState, token)
        } catch (error) {
          // 处理错误
          clearInterval(this.timer)
          this.codeState = 4 // 发生异常的情况下 把状态码设置成失效
        }
      }
      // 记录当前的标记
      this.timer = setInterval(() => {
        // 检查逻辑
        checkState()
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.qrcode_layer {
    position: absolute;
    width: 150px;
    height: 150px;
    left: 50%;
    top: 50%;
    transform: translate(-75px, -75px);
    opacity: 0.9;
    background: #e1dede;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      font-size: 40px;
      padding: 10px;
    }
  }
  .scan_success {
    i {
      color: #67C23A;
    }
  }
  .timeout {
    i {
      color: #F56C6C;
    }
  }
.qrcode-login {
    width: 350px;
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
  }
.login-container{
  display: flex;
  align-items: stretch;
  height: 100vh;
  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
  }
  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;

    .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

   ::v-deep .el-input {
      width: 350px;
      height: 44px;
      .el-input__inner {
        background: #f4f5fb;
      }
    }

    ::v-deep .el-checkbox {
      color: #606266;
    }
  }
}
</style>
